using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
using Command.Host.Infrastructure;
using Jason.ComponentModel;
using Jason.Configuration;
using Jason.Factories;
using Jason.Runtime;
using Jason.Server.WcfServices;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using StructureMap;
using Topics.Radical.Linq;
using Topics.Radical.Reflection;

namespace Command.HostRole
{
    public class WorkerRole : RoleEntryPoint
    {
        private ServiceHost _host;
        private DiagnosticMonitor _monitor;

        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("Command.HostRole entry point called", "Information");
            //StartJasonEnvironment();

            while (true)
            {
                Thread.Sleep(10000);
                Trace.WriteLine("Working", "Information");
            }
        }

        public override bool OnStart()
        {
            ServicePointManager.DefaultConnectionLimit = 12;

            CloudStorageAccount.SetConfigurationSettingPublisher((name, setter) => setter(RoleEnvironment.GetConfigurationSettingValue(name)));

            var diagnostics = new AzureDiagnostics.TableStorageTraceListener();
            diagnostics.Name = "dotnetmarche";

            Trace.Listeners.Add(diagnostics);
            Trace.AutoFlush = true;
           
            StartJasonEnvironment();
            //RoleEnvironment.Changing += RoleEnvironmentChanging;
            return base.OnStart();
        }

        public override void OnStop()
        {
            _host.Close();
            base.OnStop();
        }

        private void StartJasonEnvironment()
        {
            try
            {
                var bootsrapper = new ServerBootstrapper(AppDomain.CurrentDomain.BaseDirectory);
                var serviceProvider = bootsrapper.Boot();

                Trace.TraceInformation("Starting WCF service host...");
                var endpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["External"].IPEndpoint;
                
                var uri = new Uri(String.Format("http://{0}/commands", endpoint));
                _host = new JasonServiceHost(serviceProvider, typeof(WorkerService), uri);

                _host.Open();
                Trace.TraceInformation("WCF service host started successfully.");
            }
            catch (TimeoutException timeoutException)
            {
                Trace.TraceError("The service operation timed out. {0}", timeoutException.Message);
            }
            catch (CommunicationException communicationException)
            {
                Trace.TraceError("Could not start WCF service host. {0}", communicationException.Message);
            }
            catch (Exception exception)
            {
                Trace.TraceError("Generic error. {0}", exception.Message);
            }
        }
    }
}
